package tcpx

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"net"
	"strconv"

	"std/netx"

	"github.com/gookit/color"
)

type TcpTemp struct {
}

func (t TcpTemp) TcpClient(ii int) {
	conn, err := net.Dial("tcp", net.JoinHostPort(netx.Ip.String(), strconv.Itoa(netx.Port)))
	if err != nil {
		fmt.Println("err :", err)
		return
	}
	defer conn.Close() // 关闭连接
	buf := make([]byte, 1024)
	for i := 0; i < 10; i++ {
		_, err = conn.Write([]byte(strconv.Itoa(ii) + ":-->" + strconv.Itoa(i))) // 发送数据
		if err != nil {
			fmt.Println("client write failed, err:", err)
			return
		}
		n, err := conn.Read(buf)
		if err != nil {
			fmt.Println("client recv failed, err:", err)
			return
		}
		color.Greenln("recv", string(buf[:n]))
	}
}
func (t TcpTemp) TcpServer() {
	listenTCP, err := net.ListenTCP("tcp",
		&net.TCPAddr{
			IP:   netx.Ip,
			Port: netx.Port,
		},
	)
	if err != nil {
		panic(err)
	}
	defer listenTCP.Close()
	for {
		conn, err := listenTCP.Accept() // 建立连接
		if err != nil {
			fmt.Println("accept failed, err:", err)
			continue
		}
		go t.process(conn) // 启动一个goroutine处理连接
	}
}
func (t TcpTemp) process(conn net.Conn) {
	defer conn.Close() // 关闭连接
	reader := bufio.NewReader(conn)
	var buf [128]byte
	for {
		n, err := reader.Read(buf[:]) // 读取数据
		if err != nil && errors.Is(err, io.EOF) {
			fmt.Println("read from client failed, err:", err)
			break
		}
		recvStr := string(buf[:n])
		fmt.Println("收到client端发来的数据：", recvStr)
		conn.Write([]byte(recvStr)) // 发送数据
	}
}
